package com.iwhalecloud.bss.kite.cucc.common.util.attackUtil;

import com.ztesoft.zsmart.core.log.ZSmartLogger;

import java.util.Map;
import java.util.UUID;


@SuppressWarnings("all")
public class KiteAttackSignKey {
    private static final ZSmartLogger log = ZSmartLogger.getLogger(KiteAttackSignKey.class);

    // 这个值不要修改,因为新后端也是用这个值
    public static final String SIGN_KEY_ENCRPT_KEY = "4qpl0f05gdnb";

    /**
     * 为请求数据计算SHA256签名，并与请求中的singKey Header比对是否一致，防止拦截、修改报文攻击 生成签名请求数据算法为：
     * 所有数据拆包成key-value对，若为多层结构，以a.b.c形式拆成独立的k-v结构，若其中有List结构，List中的每一项用下标表达key值
     * ，如a.b.0或a.b.1.c 然后将所有（key-value）以字符顺序排序排序，再用key=value;将所有数据连接起来作为签名输入
     *
     * @param httpServletRequest
     * @return
     */
    public String getSignKey(Map<String, String> busiMap) {
        /*StringBuffer body = new StringBuffer();
        Map<String, Object> formatData = new HashMap<>();
        getSignData("", busiMap, formatData);
        List<String> keys = Lists.newArrayList(formatData.keySet());
        keys.sort(Comparator.naturalOrder());
        for (int i = 0; i < keys.size(); ++i) {
            Object value = formatData.get(keys.get(i));
            if (!(value == null || "".equals(value))) {
                body.append(keys.get(i) + "=" + value + ";");
            }
        }
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(body.toString().getBytes("UTF-8"));
            String _signKey = getUUID() + byte2Hex(messageDigest.digest());
            return getSignKeyEncrptKey(_signKey);
        } catch (NoSuchAlgorithmException e) {
            log.error("getSignKey：{}", e.getLocalizedMessage(), e);
        } catch (UnsupportedEncodingException e) {
            log.error("getSignKey：{}", e.getLocalizedMessage(), e);
        }*/
        return null;
    }

    private void getSignData(String keyPrefix, Object obj, Map<String, Object> signData) {
        /*if (obj instanceof Map) {
            ((Map) obj).keySet().forEach((key) -> {
                getSignData(!StringUtils.isEmpty(keyPrefix) ? keyPrefix + "." + key : key.toString(),
                    ((Map) obj).get(key), signData);
            });
        } else if (obj instanceof List) {
            for (int idx = 0; idx < ((List) obj).size(); ++idx) {
                Object item = ((List) obj).get(idx);
                getSignData(!StringUtils.isEmpty(keyPrefix) ? keyPrefix + "." + idx : String.valueOf(idx), item,
                    signData);
            }
        } else {
            signData.put(keyPrefix, obj);
        }*/
    }

    private String getParamString(String key, String[] values) {
        if (values.length == 1) {
            return key + "=" + values[0] + ";";
        } else if (values.length > 1) {
            StringBuffer valString = new StringBuffer();
            for (int i = 0; i < values.length; ++i) {
                valString.append(key + "." + i + "=" + values[i] + ";");
            }

            return valString.toString();
        } else {
            return "";
        }
    }

    private String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    private String getUUID() {
        String uuId = UUID.randomUUID().toString().trim().replace("-","");
        String uuid = uuId.substring(0,16);
        return uuid;
    }

    private String getSignKeyEncrptKey(String signKey){
        DesEncrypt desEncrypt = new DesEncrypt(KiteAttackSignKey.SIGN_KEY_ENCRPT_KEY);
        signKey = desEncrypt.encrypt(signKey);
        return signKey;
    }
}
